package per.turtle.system.controller;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import per.turtle.common.core.constant.CommonConstants;
import per.turtle.common.core.utils.SecurityUtils;
import per.turtle.common.core.web.controller.BaseController;
import per.turtle.common.core.web.entity.CommonResult;
import per.turtle.common.log.annotation.Log;
import per.turtle.common.log.enums.BusinessType;
import per.turtle.common.security.annotation.PreAuthorize;
import per.turtle.system.entity.SysMenu;
import per.turtle.system.service.ISysMenuService;
import per.turtle.system.vo.RouterVo;

import java.util.List;

/**
 * @author turtle
 */
@AllArgsConstructor
@Api(value = "menu", tags = {"menu_菜单管理模块"})
@RequestMapping("menu")
@RestController
public class SysMenuController extends BaseController {

    private final ISysMenuService menuService;

    @ApiOperation(value = "新增菜单", notes = "新增菜单")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping("add")
    @PreAuthorize(hasPermission = "system:menu:add")
    public CommonResult<Void> add(@Validated @RequestBody SysMenu menu) {
        if (!menuService.checkMenuNameUnique(menu)) {
            return CommonResult.error("新增菜单【" + menu.getMenuName() + "】失败，菜单名称已存在");
        } else if (!menu.getIsFrame() && !StrUtil.startWithAny(menu.getPath(), CommonConstants.HTTP, CommonConstants.HTTPS)) {
            return CommonResult.error("新增菜单【" + menu.getMenuName() + "】失败，地址必须以http(s)://开头");
        }
        return result(menuService.insertMenu(menu));
    }

    @ApiOperation(value = "修改菜单", notes = "修改菜单")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PreAuthorize(hasPermission = "system:menu:edit")
    @PutMapping("edit")
    public CommonResult<Void> edit(@Validated @RequestBody SysMenu menu) {
        if (!menuService.checkMenuNameUnique(menu)) {
            return CommonResult.error("修改菜单【" + menu.getMenuName() + "】失败，菜单名称已存在");
        } else if (!menu.getIsFrame() && !StrUtil.startWithAny(menu.getPath(), CommonConstants.HTTP, CommonConstants.HTTPS)) {
            return CommonResult.error("修改菜单【" + menu.getMenuName() + "】失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return CommonResult.error("修改菜单【" + menu.getMenuName() + "】失败，上级菜单不能选择自己");
        }
        return result(menuService.updateMenu(menu));
    }

    @ApiOperation(value = "根据菜单编号获取详细信息", notes = "根据菜单编号获取详细信息")
    @GetMapping("{menuId}")
    @PreAuthorize(hasPermission = "system:menu:query")
    public CommonResult<SysMenu> getInfo(@PathVariable String menuId) {
        return CommonResult.success(menuService.selectMenuById(menuId));
    }

    @ApiOperation(value = "获取用户菜单信息", notes = "获取用户菜单信息")
    @GetMapping("getUserMenus")
    public CommonResult<List<RouterVo>> getUserMenus() {
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(SecurityUtils.getUserId());
        return CommonResult.success(menuService.buildMenus(menus));
    }

    @ApiOperation(value = "获取菜单列表或分页", notes = "获取菜单列表或分页（区别于是否传入分页参数）")
    @PostMapping("list")
    @PreAuthorize(hasPermission = "system:menu:list")
    public CommonResult<List<SysMenu>> list(@RequestBody SysMenu menu) {
        List<SysMenu> menus = startPage(s -> menuService.selectMenuList(menu, SecurityUtils.getUserId()));
        return CommonResult.success(menus);
    }

    @ApiOperation(value = "删除菜单", notes = "删除菜单")
    @DeleteMapping("{menuId}")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @PreAuthorize(hasPermission = "system:menu:remove")
    public CommonResult<Void> remove(@PathVariable("menuId") String menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return CommonResult.error("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return CommonResult.error("菜单已分配,不允许删除");
        }
        return result(menuService.deleteMenuById(menuId));
    }

}